package com.example.demo.controller;

import com.example.demo.common.Face;
import com.example.demo.common.Face_Rec;
import com.example.demo.common.Result;
import com.example.demo.entity.Family;
import com.example.demo.entity.Log;
import com.example.demo.mapper.FamilyMapper;
import com.example.demo.mapper.LogMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.UUID;

/**
 * @author lai
 * @data 2021/12/8
 * @apiNote
 */

@RestController
@RequestMapping("/face")
public class FaceController {

    // 调用base64解析类

    Face face = new Face();

    // 调用人脸识别类

    Face_Rec face_rec = new Face_Rec();

    // 设置图片保存路径

    String path = System.getProperty("user.dir")+"\\src\\main\\resources\\files\\";

    // 生成唯一标识符为图片命名

    String imgClassPath = path.concat(UUID.randomUUID().toString()).concat(".jpg");

    // 当前日期和时间,sql类型

    Timestamp timestamp = new Timestamp(System.currentTimeMillis());

    // 引入LogMapper和FamilyMapper

    @Resource
    LogMapper logMapper ;

    @Resource
    FamilyMapper familyMapper;

    /**
     * 人脸识别
     *
     * base64：前端传来的用户人脸图像的base64数据
     * */
    @PostMapping
    public Result<?> doFace(@RequestBody String base64){
        Result result = null;
        String portrait = face_rec.face_res(face.getByt(base64));
        try {
            if (!portrait.equals("失败")){
                System.out.println("识别成功！！");
                // 获取识别成功的家长的信息
                Family family = familyMapper.selectByPortrait("http://localhost:9090/files/" +portrait);
                // 将该家长信息存入日志数据库
                Log log = new Log();
                log.setFamilyId(family.getId());
                log.setFamilyName(family.getName());
                log.setOntime(timestamp);
                logMapper.insert(log);
                // 返回结果
                result = Result.success();
            }
            else {
                System.out.println("识别失败！！");
                result = Result.fail();
            }
        }
        catch (Exception e){
            System.out.println("请重新识别");
            System.out.println(e);
            result = Result.fail();
        }
        return result;
    }


//    @PostMapping("saveFace")
//    public void saveFace(@RequestBody String base64) throws IOException {
//        // 生成jpg图片,存入指定路径
//        OutputStream out = new FileOutputStream(imgClassPath);
//        System.out.println(imgClassPath);
//        out.write(face.getByt(base64));
//        out.flush();
//        out.close();
//        System.out.println("保存成功");
//    }
}
